package imageswipe.navigation.dot 
{
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import imageswipe.events.SelectIndexEvent;
	import imageswipe.vo.DotIndicatorVO;
	import imageswipe.vo.DotVO;
	
	/**
	 * ...
	 * @author 
	 */
	[Event(name = "indexChanged", type = "imageswipe.events.SelectIndexEvent")]
	
	public class DotIndicator extends Sprite 
	{
		private var _dataProvider:DotIndicatorVO;
		private var _vDot:Vector.<Dot>;
		
		public function DotIndicator() 
		{
		}
		
		private function _draw():void 
		{
			if (!_dataProvider || !_dataProvider is DotIndicatorVO) return;
			while (this.numChildren) this.removeChildAt(0);
			_vDot = new Vector.<Dot>(_dataProvider.numberOfDots);
			for (var i:int = 0; i < _vDot.length; i++) 
			{
				_dataProvider.vDotVO[i] = new DotVO;
				_vDot[i] = new Dot;
				_vDot[i].dataProvider = _dataProvider.vDotVO[i];
				_vDot[i].addEventListener(MouseEvent.CLICK, _onDotClicked);
				addChild(_vDot[i]);
			}
			_positionDots();
			_setIndex(_dataProvider.indexSelected);
			//trace(this, "dot index set to:::", _dataProvider.indexSelected);
		}
		
		private function _onDotClicked(e:MouseEvent):void 
		{
			var __dot:Dot = Dot(e.currentTarget);
			var __index:int = _vDot.indexOf(__dot);
			
			//_dataProvider.indexSelected = __index;
			
			if (_dataProvider.indexSelected != __index)
			{
				dispatchEvent(new SelectIndexEvent(SelectIndexEvent.INDEX_CHANGED, __index));
			}
		}
		
		private function _positionDots():void 
		{
			var __dot:Dot;
			
			for (var i:int = 0; i < _vDot.length; i++) 
			{
				__dot = _vDot[i];
				__dot.x = i * _dataProvider.dotPaddingX;
			}
		}
		
		private function _setIndex(__index:int = 0):void 
		{
			//trace(this, "setIndex::", __index);
			_dataProvider.vDotVO[__index].selectedState = true;
			Dot(_vDot[__index]).dataProvider = _dataProvider.vDotVO[__index];
		}
		
		public function set dataProvider(value:DotIndicatorVO):void 
		{
			if (!value || !value is DotIndicatorVO) return;
			_dataProvider = value;
			_draw();
		}
		
	}

}